/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;

import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author RasJLK
 */
@Stateless
public class CustomerFacade extends AbstractFacade<Customer> {

    @PersistenceContext(unitName = "CustOrederApp-ejbPU")
    private EntityManager em;
    @EJB
    private  CustomerOrderFacade cof;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CustomerFacade() {
        super(Customer.class);
    }

    public Customer getCustomerById(Long id) {
        Customer c = null;
        List<Customer> list = findAll();
        Iterator it = list.iterator();

        while (it.hasNext()) {
            Customer d = (Customer) it.next();
            if (d.getId().compareTo(id) == 0) {
                c = d;
                break;
            }
        }

        return c;
    }

    public void removeById(Long id) {
        Customer c = getCustomerById(id);
        
        if (c != null) {
            try {
                List<CustomerOrder> orders = cof.findAll();
                for (Iterator it = orders.iterator(); it.hasNext();) {
                    CustomerOrder o = (CustomerOrder) it.next();
                    if (o.getCustomer().equals(c)) {
                        cof.remove(o);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            remove(c);
        }
    }
}
